//
//  CollectViewController.m
//  aMoment
//
//  Created by dllo on 15/10/15.
//  Copyright © 2015年 LuckyHan. All rights reserved.
//

#import "CollectViewController.h"
#import "AllHeaderFiles.h"

@interface CollectViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *dataSourceArray;
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)NSString *keyword;
@property(nonatomic, assign)NSInteger flag;
@end

@implementation CollectViewController

- (void)dealloc
{
    [_tableView release];
    [_dataSourceArray release];
    [_searchBar release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"我的收藏";
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back@2x"] style:UIBarButtonItemStylePlain target:self action:@selector(backToMenu)];//左侧按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(backToMenu)];//左侧按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;//右侧按钮
}

#pragma mark 返回菜单
- (void)backToMenu
{
    [self.navigationController popViewControllerAnimated:YES];
    [(DDMenuController *)self.view.window.rootViewController showLeftController:YES];
}

#pragma mark searchBar协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //搜索内容为空
    if ([searchText isEqualToString:@""]) {
        _flag = 0;
        [_dataSourceArray removeAllObjects];
        
        //查询数据库
        [DatabaseManager createTable];
        self.dataSourceArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
        [_tableView reloadData];
    }
    //搜索内容不为空
    else {
        _flag = 1;
        self.keyword = searchText;
        
        //模糊查询
        self.dataSourceArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecordsBySearchText:searchText]];
        [_tableView reloadData];
        
        //搜索无结果
        if (_dataSourceArray.count == 0) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有搜索到结果" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertController animated:YES completion:^{
                [alertController dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }
}

- (void)loadView
{
    [super loadView];
    self.dataSourceArray = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //创建搜索条
    self.searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    _searchBar.returnKeyType = UIReturnKeyDone;
    self.navigationItem.titleView = _searchBar;
    [_searchBar release];
}

#pragma mark cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

#pragma mark cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_flag == 1) {//搜索结果
        cell.textLabel.attributedText = [self keywordHighlight:[_dataSourceArray[indexPath.row] title]];
    }
    else {//收藏结果
        cell.textLabel.text = [_dataSourceArray[indexPath.row] title];
    }
    return cell;
}

#pragma mark 关键字高亮
- (NSMutableAttributedString *)keywordHighlight:(NSString *)title
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];
    NSRange range = [title rangeOfString:_keyword];
    [attributedString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, nil] range:range];
    return attributedString;
}

#pragma mark cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    Record *currentRecord = [[Record alloc] init];
    NSMutableArray *recordArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
    
    //找到点击的这个cell在数据库中的记录
    for (Record *record in recordArray) {
        if ([cell.textLabel.text isEqualToString:record.title]) {
            currentRecord = record;
            break;
        }
    }
    
    //判断是哪种详情页
    if ([currentRecord.itemName isEqualToString:@"Home"]) {
        HomeDetailsViewController *homeVC = [[HomeDetailsViewController alloc] init];
        [self.navigationController pushViewController:homeVC animated:YES];
        homeVC.contentId = currentRecord.contentId;
        [homeVC release];
    }
    else if ([currentRecord.itemName isEqualToString:@"Store"]) {
        StoreDetailsViewController *storeVC = [[StoreDetailsViewController alloc] init];
        [self.navigationController pushViewController:storeVC animated:YES];
        storeVC.contentID = currentRecord.contentId;
        [storeVC release];
    }
    else {
        TimelineDetailsViewController *timelineVC = [[TimelineDetailsViewController alloc] init];
        [self.navigationController pushViewController:timelineVC animated:YES];
        timelineVC.contentId = currentRecord.contentId;
        [timelineVC release];
    }
}

#pragma mark 删除cell
//开启动画
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
}
//允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//设置编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//开始编辑
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *recordArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
        for (Record *record in recordArray) {
            if ([cell.textLabel.text isEqualToString:record.title]) {
                [DatabaseManager deleteRecord:record.contentId];
                break;
            }
        }
        self.dataSourceArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
        
        if (_dataSourceArray.count == 0) {
            _tableView.tableHeaderView = [self createHeaderView];
        } else {
            _tableView.tableHeaderView = nil;
        }
        
        [_tableView reloadData];
    }
}

#pragma mark 视图即将出现
- (void)viewWillAppear:(BOOL)animated
{
    //查询数据库
    [DatabaseManager createTable];
    self.dataSourceArray = [NSMutableArray arrayWithArray:[DatabaseManager selectRecords]];
    
    if (_dataSourceArray.count == 0) {
        _tableView.tableHeaderView = [self createHeaderView];
    } else {
        _tableView.tableHeaderView = nil;
    }
    
    [_tableView reloadData];
}

#pragma mark 创建headerView
- (UILabel *)createHeaderView
{
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    headerLabel.text = @"什么都没有, 快去收藏吧~";
    headerLabel.textAlignment = NSTextAlignmentCenter;
    headerLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    return headerLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
